package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.Result;
import com.gaohe.pojo.Notice;
import com.gaohe.pojo.VO.NoticeVo;
import com.gaohe.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    @GetMapping("/page")
    public Result page(
            @RequestParam("page") Integer page,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(value = "title", required = false) String title
    ) {
        //1.创建分页对象
        Page<Notice> noticePage = new Page<>(page, pageSize);
        //2.构造条件
        LambdaQueryWrapper<Notice> qw = new LambdaQueryWrapper<>();
        qw.like(Objects.nonNull(title) && !title.isBlank(),
                Notice::getTitle, title);
        qw.orderByDesc(Notice::getUpdateTime);
        //3.查询
        noticeService.page(noticePage, qw);
        //4.返回
        return Result.success(noticePage);
    }

    /**
     * 根据 id 查询 notice and detail
     *
     * @param noticeId
     * @return
     */
    @GetMapping("/{id}")
    public Result getNoticeAndDetailByNoticeId(@PathVariable("id") Long noticeId) {
        return noticeService.getNoticeAndDetailByNoticeId(noticeId);
    }

    /**
     * 根据noticeId 修改 notice and noticeDetail
     *
     * @param noticeVo
     * @return
     */
    @PutMapping
    public Result modifyNoticeAndDetailByNoticeId(@RequestBody NoticeVo noticeVo) {
        return noticeService.modifyNoticeAndDetailByNoticeId(noticeVo);
    }

    @DeleteMapping
    public Result deleteNoticeAndDetailByNoticeId(@RequestParam("id") Long noticeId) {
        return noticeService.deleteNoticeAndDetailByNoticeId(noticeId);
    }
}
